package Leetcode第一期;

/**
 * @author : K k
 * @date : 12:01 2020/5/6
 */
public class 合并两个排序的链表_25 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    //迭代
    public ListNode mergeTwoListsA(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        ListNode tmp = result;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                result.next = l1;
                l1 = l1.next;
            } else {
                result.next = l2;
                l2 = l2.next;
            }
            result = result.next;
        }
        while (l1 != null) {
            result.next = l1;
            l1 = l1.next;
            result = result.next;
        }

        while (l2 != null) {
            result.next = l2;
            l2 = l2.next;
            result = result.next;
        }
        return tmp.next;
    }

    //递归
    public ListNode mergeTwoListsB(ListNode l1, ListNode l2) {
        if (l1==null){
            return l2;
        }
        if (l2==null){
            return l1;
        }

        if (l1.val<l2.val){
            l1.next=mergeTwoListsB(l1.next,l2);
            return l1;
        }else {
            l2.next=mergeTwoListsB(l1,l2.next);
            return l2;
        }

    }
}